package rational;

public class Rational {
    int numerator, denominator;
    Rational(int new_numerator, int new_denominator){
        updateRational(new_numerator, new_denominator);
    }
     void printRational(){
        if (denominator == 1) {
            System.out.printf("%d\n", numerator);
        }
        else {
            System.out.printf("%d/%d\n", numerator, denominator);
        }
     }
     void printReal(){
         System.out.printf("%.1f\n", (float)numerator/(float)denominator);
     }
     void add(Rational new_rational){
        int lcm = calculateLCM(denominator, new_rational.denominator);
        numerator = numerator * lcm / denominator + new_rational.numerator * lcm / new_rational.denominator;
        updateRational(numerator, lcm);
     }
    void sub(Rational new_rational){
        int lcm = calculateLCM(denominator, new_rational.denominator);
        numerator = numerator * lcm / denominator - new_rational.numerator * lcm / new_rational.denominator;
        updateRational(numerator, lcm);
    }
    void mul(Rational new_rational){
        numerator = numerator * new_rational.numerator;
        denominator = denominator * new_rational.denominator;
        updateRational(numerator, denominator);
    }
    void div(Rational new_rational){
        numerator = numerator * new_rational.denominator;
        denominator = denominator * new_rational.numerator;
        updateRational(numerator, denominator);
    }
    void updateRational(int new_numerator, int new_denominator){
        int gcr = calculateGCR(new_numerator, new_denominator);
        numerator = new_numerator / gcr;
        denominator = new_denominator / gcr;
    }
     int calculateGCR(int a, int b){
         int middle1, middle2, middle3;
         if (a > b) {
             middle1 = a;
             middle2 = b;
         }
         else {
             middle1 = b;
             middle2 = a;
         }
         middle3 = middle1 % middle2;
         while (middle3!=0){
             middle1 = middle2;
             middle2 = middle3;
             middle3 = middle1 % middle2;
         }
         return middle2;
     }
    int calculateLCM(int a, int b){
        return a * b / calculateGCR(a, b);
    }
}
